function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  const hour = parseInt(time / 3600, 10)
  time %= 3600
  const minute = parseInt(time / 60, 10)
  time = parseInt(time % 60, 10)
  const second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }

  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}

function fib(n) {
  if (n < 1) return 0
  if (n <= 2) return 1
  return fib(n - 1) + fib(n - 2)
}

function formatLeadingZeroNumber(n, digitNum = 2) {
  n = n.toString()
  const needNum = Math.max(digitNum - n.length, 0)
  return new Array(needNum).fill(0).join('') + n
}

function formatDateTime(date, withMs = false) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const ms = date.getMilliseconds()

  let ret = [year, month, day].map(value => formatLeadingZeroNumber(value, 2)).join('-') +
    ' ' + [hour, minute, second].map(value => formatLeadingZeroNumber(value, 2)).join(':')
  if (withMs) {
    ret += '.' + formatLeadingZeroNumber(ms, 3)
  }
  return ret
}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i], 10)
    const num2 = parseInt(v2[i], 10)

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

function jsonToHtml(obj, indent) {
  const pad = n => '&nbsp;'.repeat(n * 4);
  if (Array.isArray(obj)) {
    let arr = '[<br>';
    obj.forEach((item, i) => {
      arr += pad(indent + 1) + jsonToHtml(item, indent + 1);
      if (i < obj.length - 1) arr += ',<br>';
    });
    arr += '<br>' + pad(indent) + ']';
    return arr;
  } else if (typeof obj === 'object' && obj !== null) {
    let str = '{<br>';
    const keys = Object.keys(obj);
    keys.forEach((key, i) => {
      str += pad(indent + 1) +
        `<span style="color:#c00;">"${key}"</span>: ` +
        jsonToHtml(obj[key], indent + 1);
      if (i < keys.length - 1) str += ',<br>';
    });
    str += '<br>' + pad(indent) + '}';
    return str;
  } else if (typeof obj === 'string') {
    return `<span style="color:#080;word-wrap: break-word;">"${obj}"</span>`;
  } else if (typeof obj === 'number') {
    return `<span style="color:#00c;word-wrap: break-word;">${obj}</span>`;
  } else if (typeof obj === 'boolean') {
    return `<span style="color:#a50;">${obj}</span>`;
  } else if (obj === null) {
    return `<span style="color:#999;">null</span>`;
  }
  return '';
}

function createApiTxt(data) {
  return new Promise((resolve,reject) => {
    wx.request({
      url: 'http://10.10.45.95:8080/api/txt',
      data,
      timeout:20000,
      method:'POST',
      success:(res)=>{
        resolve(res)
      },
      fail:(e)=>{
        reject(e)
      }
    })
  })
}

module.exports = {
  formatTime,
  formatLocation,
  fib,
  formatDateTime,
  compareVersion,
  jsonToHtml,
  createApiTxt
}
